package idv.etrex.display.object 
{
	import flash.events.EventDispatcher;
	import idv.etrex.events.PlayerEvent;
		
		/** 
		 * 動畫撥放完時丟出
		 * @eventType Complete;
		 */
		[Event(name = "Complete", type = "idv.etrex.events.PlayerEvent")]
		
	/**
	 * SerialPlayList 按照順序播放 IPlayer，一個播放完就撥下一個，直到最後一個播放完就會丟出Complete事件。
	 * @author etrex
	 */
	public class SerialPlayList extends EventDispatcher implements IPlayer
	{
		private var players:Array = new Array();
		private var playingIndex :int;
		private var _isPlaying :Boolean;
		private var _onComplete:Function = function():void { };
		
		/**
		 * 是否正在播放
		 */
		public function get isPlaying():Boolean{
			return _isPlaying;
		}
		
		/**
		 * 在丟出DynamicStrokeEvent.COMPLETE事件前會先執行
		 */
		public function set onComplete(value:Function):void {
			_onComplete = value;
		}
		
				
		/**
		 * 傳入一連串的 IPlayer 建構 PlayList
		 */
		public function SerialPlayList(...players) 
		{
			this.players = players;
			playingIndex = 0;
		}
		
		/**
		 * 播放
		 */
		public function play():void {
			_isPlaying = true;
			var ip:IPlayer = players[playingIndex];
			ip.addEventListener(PlayerEvent.COMPLETE, completeHandler);
			ip.play();
		}

		/**
		 * 從頭播放
		 */
		public function replay():void  {
			stop();
			play();
		}
		
		/**
		 * 暫停播放
		 */
		public function pause():void  {
			_isPlaying = false;
			var ip:IPlayer = players[playingIndex];
			ip.removeEventListener(PlayerEvent.COMPLETE, completeHandler);
			ip.pause();
		}
		
		/**
		 * 停止播放
		 */
		public function stop():void  {
			_isPlaying = false;
			var ip:IPlayer = players[playingIndex];
			ip.removeEventListener(PlayerEvent.COMPLETE, completeHandler);
			
			for (var i:int = 0 ; i <= playingIndex ; i++)
			{
				ip = players[i];
				ip.stop();
			}
			playingIndex = 0;
		}
		
		private function completeHandler(e:PlayerEvent):void {
			var ip:IPlayer = players[playingIndex];
			ip.removeEventListener(PlayerEvent.COMPLETE, completeHandler);
			
			playingIndex ++;
			
			if (playingIndex == players.length)
			{
				playingIndex --;
				pause();
				_onComplete.apply(this);
				this.dispatchEvent(new PlayerEvent(PlayerEvent.COMPLETE));
			}
			else
			{
				var ip2:IPlayer = players[playingIndex];
				ip2.addEventListener(PlayerEvent.COMPLETE, completeHandler);
				ip2.play();
			}
		}
	}
}